/*
 * @Author: zdc 3215400595@qq.com
 * @Date: 2023-05-06 23:19:02
 * @LastEditors: zdc 3215400595@qq.com
 * @LastEditTime: 2023-05-06 23:34:41
 * @FilePath: /pipe/3.namepipe/server.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include "comm.hpp"
int main()
{
    // 1. 创建管道文件，我们今天只需要一次创建
    umask(0); //这个设置并不影响系统的默认配置，只会影响当前进程
    int n = mkfifo(fifoname.c_str(), mode);
    if(n != 0)
    {
        std::cout << errno << " : " << strerror(errno) << std::endl;
        return 1;
    }
    std::cout << "create fifo file success" << std::endl;
    
    //让服务端开启管道文件
    //打开文件(肯定打开管道)（所以需要只读权限就可以）
    int rfd = open(fifoname.c_str(),O_RDONLY);
    if(rfd < 0 )
    {
        cout << errno << " : " << strerror(errno) << endl;
        return 2;
    }
    cout<<"open fifo sucess,begin ipc"<<endl;
    char buffer[NUM];
    while(true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd,buffer,sizeof(buffer) - 1 );
        if(n > 0 )
        {
            buffer[n] = 0;
            cout<<"client#"<<buffer<<endl;
        }
        else if(n == 0)
        {
            cout<<"client quit,me too"<<endl;
            break;
        }
        else
        {
            cout << errno << " : " << strerror(errno) << endl;
            break;
        }
    }
    close(rfd);
    return 0;
}